package com.lex.crossgate.admin.modules.sys.controller;

import com.lex.crossgate.common.exception.RRException;
import com.lex.crossgate.admin.common.log.config.Log;
import com.lex.crossgate.admin.common.support.jwt.JWTUtil;
import com.lex.crossgate.common.constants.Constant;
import com.lex.crossgate.admin.common.support.shiro.MD5Utils;
import com.lex.crossgate.admin.common.utils.ShiroUtils;
import com.lex.crossgate.admin.common.base.BaseController;
import com.lex.crossgate.admin.modules.sys.entity.SysUser;
import com.lex.crossgate.admin.modules.sys.service.SysUserService;
import com.lex.crossgate.common.constants.ResponseBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * TODO: 登录
 * @author 李贝留斯
 * @email sunyadongsyd@163.com
 * @date 2018/4/24 14:42
 */
@Api(value = "/login", tags="登录模块")
@Controller
public class SysLoginController extends BaseController {
	
	@Autowired
	private SysUserService sysUserService;

	/**
	 * TODO: 登录
	 * @author 李贝留斯
	 * @param
	 * @date 2018/5/04 15:20
	 */
	@ApiOperation(value = "用户登录",notes = "PC端用户登录")
	@ApiImplicitParam(name = "userName", value = "passWord")
	@Log("登陆")
	@ResponseBody
	@PostMapping(value = "/login")
	public ResponseBean tologin(@RequestParam String userName,@RequestParam String passWord){
        SysUser sysUser = sysUserService.getByUserName(userName);
		if(sysUser.getStatus() == 0) {
			return new ResponseBean(200,"账号已被锁定,请联系管理员",null);
		}

		passWord = MD5Utils.encrypt(userName, passWord);
        if(sysUser == null || !sysUser.getPassWord().equals(passWord)) {
            return new ResponseBean(200,"用户名或密码错误",null);
        }
        if(sysUser.getPassWord().equals(passWord)){
        	//清除redis中token

        	return  new ResponseBean(200,"Login success", JWTUtil.sign(sysUser.getUserName(), sysUser.getPassWord()));
		} else {
			throw new RRException("登录异常");
		}
	}

	/**
	 * TODO: 
	 * @author 李贝留斯
	 * @email sunyadongsyd@163.com
	 * @date 2018/5/15 10:26
	 */
	@ApiOperation(value = "用户注销",notes = "PC端用户注销")
	@Log("注销")
	@PostMapping(value="/logout")
	public void logout(){

		//shiro管理的session
		Session session = ShiroUtils.getSession();
		session.removeAttribute(Constant.SYSUSER);
		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
	}
}
